import Icon from '@/components/Icons';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';

import io, { Socket } from 'socket.io-client';
import { baseURL } from '@/utils/request';
import { getToken } from '@/utils/storage';
import { Toast } from 'antd-mobile';

type MsgType = {
  type: string;
  msg: string;
  timestamp: number;
};
export default function Chat() {
  const [msg, setMsg] = useState('');
  const [msgList, setMsgList] = useState<MsgType[]>([
    // { type: 'robot', msg: 'hello', timestamp: Date.now() },
    // { type: 'user', msg: '傻逼', timestamp: Date.now() },
    // { type: 'user', msg: '傻逼', timestamp: Date.now() },
  ]);

  const [type, setType] = useState(true);

  // 声明ref保存数据
  const clientRef = useRef<Socket | null>(null);

  // 使用socket.io实现聊天功能
  useEffect(() => {
    // 创建连接
    clientRef.current = io(baseURL, {
      query: {
        token: getToken().token,
      },
      transports: ['websocket'],
    });
    // 监听连接
    clientRef.current.on('connect', () => {
      console.log('连接成功');
      // 主动发消息
      setMsgList([
        ...msgList,
        { type: 'robot', msg: 'hello,小智为您服务!', timestamp: Date.now() },
      ]);
    });
    //接收消息
    clientRef.current.on('message', (data) => {
      // console.log(data);
      setMsgList((preMsgList) => {
        // console.log(oldMsgList);
        return [...preMsgList, { type: 'robot', ...data }];
      });
    });

    window.addEventListener('scroll', () => {
      // console.log('滚动的距离', document.documentElement.scrollTop);
      // console.log(window.innerHeight);
      if (
        document.body.scrollHeight - document.documentElement.scrollTop - 20 <
        window.innerHeight
      ) {
        setType(true);
        // console.log('不超过');
      } else {
        setType(false);
      }
    }); //监听滚动事件

    return () => {
      // 关闭连接
      clientRef.current?.close();
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 发送消息
  const handleEmit = () => {
    // 判断msg为空时不能发送消息
    if (!msg.trim()) {
      Toast.show('不能发送空消息');
      return;
    }
    const newMsg = { msg, timestamp: Date.now() };
    clientRef.current?.emit('message', newMsg);
    setMsgList([...msgList, { type: 'user', ...newMsg }]);
    setMsg('');
  };

  // 回车发送消息
  const handleKeyDoen = (e: React.KeyboardEvent<HTMLSpanElement>) => {
    if (e.key === 'Enter') {
      handleEmit();
    }
  };

  useEffect(() => {
    console.log(document.body.scrollHeight);
    if (type) {
      // 添加消息回复时,滚动到最底部
      window.scrollTo({
        top: document.body.scrollHeight,
        // 设置滚动行为改为平滑的滚动
        behavior: 'smooth',
      });
    }
  }, [msgList, type]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {msgList.map((item) => {
          return item.type === 'robot' ? (
            // {/* 机器人的消息 */}
            <div className="chat-item" key={item.timestamp}>
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{item.msg}</div>
            </div>
          ) : (
            // {/* 用户的消息 */}
            <div className="chat-item user" key={item.timestamp}>
              <img
                src={'http://toutiao.itheima.net/images/user_head.jpg'}
                alt=""
              />
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>
      {/* 底部消息输入框 */}
      <div className="footer">
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            onKeyDown={(e) => handleKeyDoen(e)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleEmit}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
